import axios from 'axios'
import { ElMessage } from 'element-plus'
import * as storage from './storage'

// 创建axios实例对象，添加全局配置
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 3000
})

const TOKEN_INVALID = 'Token认证失败,请重新登录'
const NETWORK_ERROR = '网络请求异常,请稍后重试'

// 请求拦截器
service.interceptors.request.use((req) => {
  const headers = req.headers;
  const { token = "" } = storage.getItem('userInfo') || {};
  if (!headers.Authorization) headers.Authorization = 'Bearer ' + token;
  return req;
}
)

// 响应拦截器
service.interceptors.response.use((res) => {
  const { code, data, msg } = res;

  return data
  // if (code === 200) {
  //   return data;
  // } else if (code === 500001) {
  //   ElMessage.error(TOKEN_INVALID)
  //   setTimeout(() => {
  //     router.push('/login')
  //   }, 1500)
  //   return Promise.reject(TOKEN_INVALID)
  // } else {
  //   ElMessage.error(msg || NETWORK_ERROR)
  //   return Promise.reject(msg || NETWORK_ERROR)
  // }
}
)

export default service
